package com.hengxinguotong.zhihuichengjian.ui.safetystudy;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.PersonManagementAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Person;
import com.hengxinguotong.zhihuichengjian.bean.PersonRes;
import com.hengxinguotong.zhihuichengjian.customtimepicker.TimePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2018/10/31
 */

public class PersonManagementActivity extends BaseActivity implements View.OnClickListener, PersonManagementAdapter.ClickListener, PersonManagementAdapter.ItemClickListener,
        TextWatcher, RadioGroup.OnCheckedChangeListener {
    public static final String TAG = "PersonManagement";
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.input_search_et)
    HXEditTextView inputSearchEt;
    @BindView(R.id.all_time_tv)
    HXTextView allTimeTv;
    @BindView(R.id.study_rg)
    RadioGroup studyRg;
    @BindView(R.id.all_tv)
    HXTextView allTv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img)
    ImageView emptyImg;

    PullableRecyclerView dataRv;

    private List<Person> personList;
    private PersonManagementAdapter adapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    List<Person> datas = (List<Person>) msg.obj;
                    process(datas);
                    break;
            }
        }
    };
    private int pageNum = 1;
    private int isTrain = 1;//1已参加培训 2：未参加培训;
    private DayTimeEntity startDay, stopDay;
    private String startDate, endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_list_safety);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        String title = getIntent().getStringExtra("title");
        titleTv.setText(title);

        studyRg.setOnCheckedChangeListener(this);

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        personList = new ArrayList<>();
        adapter = new PersonManagementAdapter(this, personList);
        adapter.setClickListener(this);
        adapter.setItemClickListener(this);
        dataRv.setAdapter(adapter);
//        dataRv.setItemAnimator(new DefaultItemAnimator());

        inputSearchEt.addTextChangedListener(this);
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener() {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
            pageNum = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            pageNum = personList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    @OnClick({R.id.iv_back, R.id.all_time_tv, R.id.all_tv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.all_time_tv:
                Intent intent = new Intent(this, TimePickerActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.all_tv:
                startDate = "";
                endDate = "";
                allTimeTv.setText(R.string.all_time);
                inputSearchEt.setText("");
                initData();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0 && data != null) {
                startDay = (DayTimeEntity) data.getSerializableExtra("startDay");
                stopDay = (DayTimeEntity) data.getSerializableExtra("stopDay");
                processDate();
            }
        }
    }

    private void processDate() {
        startDate = dateFormat(startDay);
        endDate = dateFormat(stopDay);
        allTimeTv.setText(dateFormatExceptYear(startDay) + "—" + dateFormatExceptYear(stopDay));
        initData();
    }

    private String dateFormat(DayTimeEntity dayTimeEntity) {
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if (dayTimeEntity.getMonth() > 9) {
            dateSb.append(dayTimeEntity.getMonth() + "-");
        } else {
            dateSb.append("0" + dayTimeEntity.getMonth() + "-");
        }
        if (dayTimeEntity.getDay() > 9) {
            dateSb.append(dayTimeEntity.getDay());
        } else {
            dateSb.append("0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private String dateFormatExceptYear(DayTimeEntity dayTimeEntity) {
        StringBuffer dateSb = new StringBuffer();
        if (dayTimeEntity.getMonth() > 9) {
            dateSb.append(dayTimeEntity.getMonth() + "/");
        } else {
            dateSb.append("0" + dayTimeEntity.getMonth() + "/");
        }
        if (dayTimeEntity.getDay() > 9) {
            dateSb.append(dayTimeEntity.getDay());
        } else {
            dateSb.append("0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    @Override
    public void onClick(Object object) {
        Person person = (Person) object;
        if (person == null) {
            return;
        }
        Intent intent = new Intent(this, StudyDetailActivity.class);
        intent.putExtra("person", person);
        startActivityForResult(intent, 2);
    }

    @Override
    public void onItemClick(Object object) {
        Person person = (Person) object;
        if (person == null) {
            return;
        }
        Intent intent = new Intent(this, PersonDetailActivity.class);
        intent.putExtra("person", person);
        startActivityForResult(intent, 1);
    }

    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                queryList();
            }
        }, 500);
    }

    private void queryList() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("startDate", startDate);
            jsonObject.put("endDate", endDate);
            jsonObject.put("pageNum", pageNum + "");
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("commonField", inputSearchEt.getEditableText().toString());
            jsonObject.put("isTrain", isTrain);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData("加载中…", this, "/thridPerson/queryList/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    PersonRes personRes = gson.fromJson(json, PersonRes.class);
                    if (personRes.getStatus() == 1) {
                        List<Person> datas = personRes.getValue();
                        if (datas == null) {
                            datas = new ArrayList<Person>();
                        }
                        Message message = handler.obtainMessage();
                        message.what = 0;
                        message.obj = datas;
                        message.sendToTarget();
                    } else {
                        showToast(personRes.getMsg());
                        if (pageNum == 1) {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                } else {
                    showToast(R.string.system_erro);
                    if (pageNum == 1) {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast(R.string.system_erro);
                }
                if (pageNum == 1) {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void process(List<Person> datas) {
        if (pageNum == 1) {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            personList = datas;
        } else {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            personList.addAll(datas);
        }
        showEmptyView(personList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT) {
            refreshList.setPullUpEnable(true);
        } else {
            refreshList.setPullUpEnable(false);
        }
        adapter.setDataList(personList);
    }

    private void showEmptyView(boolean isEmpty) {
        if (isEmpty) {
            emptyImg.setVisibility(View.VISIBLE);
        } else {
            emptyImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        pageNum = 1;
        personList.clear();
        initData();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.has_study:
                isTrain = 1;//1已参加培训 2：未参加培训;
                break;
            case R.id.no_study:
                isTrain = 2;//1已参加培训 2：未参加培训;
                break;
        }
        pageNum = 1;
        personList.clear();
        initData();
    }
}
